package org.lisz.order.service.impl;

import com.alibaba.cloud.nacos.discovery.NacosServiceDiscovery;
import lombok.extern.slf4j.Slf4j;
import org.lisz.order.feign.ProductFeignClient;
import org.lisz.order.po.Order;
import org.lisz.order.service.OrderService;
import org.lisz.product.po.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Override
    public Order crateOrder(Long productId, Long userId) {
//        Product product = getProductById(productId);
        Product product = productFeignClient.getProducts(productId);
        Order order = new Order();
        order.setId(1L);
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setUserId(userId);
        order.setNickName("lisz");
        order.setAddress("上林天宫");
        order.setProducts(List.of(product));
        return order;
    }

    private Product getProductById(Long productId) {
//        List<ServiceInstance> instances = discoveryClient.getInstances("product-service");
//        ServiceInstance serviceInstance = instances.get(0);
//        String host = "http://"+serviceInstance.getHost();
//        int port = serviceInstance.getPort();
//        String url = host + ":" + port + "/product/" + productId;
//        String url = "http://product-service/product/" + productId;
//        log.info("请求路径：" + url);
//        Product product = restTemplate.getForObject(url, Product.class);
        return productFeignClient.getProducts(productId);
    }

    private Product getProductByIdWithLoadBalancer(Long productId) {
        ServiceInstance serviceInstance = loadBalancerClient.choose("product-service");
        String host = "http://"+serviceInstance.getHost();
        int port = serviceInstance.getPort();
        String url = host + ":" + port + "/product/" + productId;
        log.info("请求路径：" + url);
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }
}
